<template>
	<div>
		<el-row :gutter="10" style="width: 100%">
			<el-col :span="4" v-if="roleIds.includes(1)">
				<el-card shadow="hover">
					<el-aside style="width: 100%">
						<el-scrollbar>
							<el-input :prefix-icon="search" v-model="filterText" placeholder="请输入部门名称" clearable size="default" />
							<el-tree
								ref="treeRef"
								class="filter-tree"
								:data="data.deptData"
								:props="data.deptProps"
								:highlight-current="true"
								:expand-on-click-node="false"
								default-expand-all
								:filter-node-method="deptFilterNode"
								@node-click="handleNodeClick"
							/>
						</el-scrollbar>
					</el-aside>
				</el-card>
			</el-col>
			<el-col :span="roleIds.includes(1)?20:24">
				<el-card shadow="hover">
					<template #header>
						<span>{{ data.curDeptName || '全部' }}</span>
					</template>
					<div class="system-dept-search mb15">
						<el-form :inline="true">
							<el-form-item label="小区名 / 地址">
								<el-input size="default" v-model="data.queryParams.keyWord" clearable placeholder="请输入关键字" />
							</el-form-item>

							<el-form-item>
								<el-button size="default" type="primary" class="ml10" @click="search"
									><el-icon> <ele-Search /> </el-icon>查询
								</el-button>
								<el-button size="default" class="ml10" type="success" @click="add">
									<el-icon> <ele-FolderAdd /> </el-icon>新增</el-button
								>
							</el-form-item>
						</el-form>
					</div>

					<el-table :border="true" ref="table" :data="data.tableData.list" height="calc(100vh - 380px)">
						<el-table-column type="index" label="#" width="55" />
						<el-table-column label="小区名称" prop="name" width="200px" />
						<el-table-column label="所属组织" width="180px">
							<template #default="{ row }">
								<span v-if="row.deptId">{{ row.deptName }}</span>
							</template>
						</el-table-column>
						<el-table-column label="小区地址" prop="address" min-width="300px" />

						<el-table-column label="经纬度" prop="longitude" width="180px">
							<template #default="{ row }">
								{{ [row.longitude, row.latitude].join(',') }}
							</template>
						</el-table-column>

						<el-table-column label="操作" column-key="operation" width="150" fixed="right">
							<template #default="{ row }">
								<el-popconfirm title="确定要转移此小区？" width="200px" @confirm="toMove(row)">
									<template #reference>
										<el-button type="warning" plain text bg size="small" v-auth="'community:transfer'"> 转移 </el-button>
									</template>
								</el-popconfirm>

								<el-button @click="doEdit(row)" type="primary" plain text bg size="small" v-auth="'community:update'"> 编辑 </el-button>
								<el-button v-if="[24,31].includes(userInfos.id)" @click="getInstallDoc(row)" type="primary" plain text bg size="small"> 安装文档 </el-button>
								<!-- v-auth="'community:installDoc'" -->
								<el-popconfirm title="确定要删除此小区？" width="200px" @confirm="doDelete(row)">
									<template #reference>
										<el-button type="danger" plain text bg size="small" v-auth="'community:delete'"> 删除 </el-button>
									</template>
								</el-popconfirm>
							</template>
						</el-table-column>
					</el-table>
					<pagination
						v-show="data.tableData.total > 0"
						:total="data.tableData.total"
						v-model:page="data.queryParams.pageNum"
						v-model:limit="data.queryParams.pageSize"
					/>
					<!-- @pagination="fetch" -->
				</el-card>
			</el-col>
		</el-row>

		<MyEdit
			ref="edit1"
			:dialog-visible="data.dialog.isVisible"
			:type="data.dialog.type"
			:treeData="data.deptData"
			@close="editClose"
			@success="editSuccess"
		/>

		<!-- 移动 -->
		<DeptMove
			ref="deptMove"
			:dialog-visible="data.isShowDeptMove"
			:potions="data.deptProps"
			@close="moveClose"
			@success="moveSuccess"
			:treeData="data.deptData"
		/>

		<!-- 导出文档 -->
		<el-drawer v-model="data.isShowInstallDoc" direction="rtl" @close="drawerClose">
			<template #header>
				<h4>安装文档</h4>
			</template>
			<template #default>
				<div class="deawerBody">
					<el-descriptions title="小区信息" :column="1" border>
						<el-descriptions-item>
							<template #label>
								<div class="cell-item">小区</div>
							</template>
							{{ data.curCommunity.name }}
						</el-descriptions-item>

						<el-descriptions-item>
							<template #label>
								<div class="cell-item">地址</div>
							</template>
							{{ data.curCommunity.address }}
						</el-descriptions-item>
						<el-descriptions-item>
							<template #label>
								<div class="cell-item">组织</div>
							</template>
							{{ data.curCommunity.deptName }}
						</el-descriptions-item>
					</el-descriptions>

					<!-- 统计安装 -->
					<div class="statistic" v-if="data.curCommunityCount">
						<div class="item">
							<div class="title">设备数量</div>
							<el-text class="mx-1" type="primary" size="large">{{ data.curCommunityCount.total }}</el-text>
						</div>
						<div class="item">
							<div class="title">待完成</div>
							<el-text class="mx-1" type="danger" size="large">{{ data.curCommunityCount.unDone }}</el-text>
						</div>
					</div>

					<el-divider></el-divider>

					<table width="100%" v-if="data.curCommunityDoc">
						<thead>
							<tr>
								<th>生成时间</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>{{ data.curCommunityDoc.createdTime }}</td>
								<td><el-link :href="getFileUrl(data.curCommunityDoc.url)" type="primary">下载</el-link></td>
							</tr>
						</tbody>
					</table>

					<el-button type="primary" style="float: right" @click="createInstallDoc(data.curCommunity)">{{
						data.curCommunityDoc ? '重新生成' : '生成文档'
					}}</el-button>
				</div>
			</template>
		</el-drawer>
	</div>
</template>

<script lang="ts" setup name="community">
import { reactive, onMounted, ref, computed, toRaw, defineComponent, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { ElMessage, ElMessageBox, ElTree } from 'element-plus';
import MyEdit from './components/Edit.vue';
import DeptMove from './components/Move.vue';
import communityApi from '/@/api/smoke/community';
import { getDeptTree } from '/@/api/system/user';
import deviceApi from '/@/api/smoke/device';
import { useUserInfo } from '/@/stores/userInfo';
import { useSmoke } from '/@/hook/index';

const { getAddress, getFileUrl } = useSmoke();
const stores = useUserInfo();
const { userInfos, roleIds, communitys } = storeToRefs(stores);

const edit1 = ref();
const deptMove = ref();

const filterText = ref('');
const treeRef = ref<InstanceType<typeof ElTree>>();

const deptFilterNode = (value: string, data: any) => {
	if (!value) return true;
	return data.deptName.includes(value);
};

const toMove = (row: any) => {
	data.isShowDeptMove = true;
	deptMove.value.form.id = row.id;
	deptMove.value.form.deptId = row.deptId ? row.deptId : '';
	deptMove.value.form.deptName = row.deptName ? row.deptName : '';
};

// 节点单击事件
const handleNodeClick = (data1: any) => {
	if (data1.parentId == 0) {
		data.queryParams.deptId = '';
		data.curDeptName = '';
	} else {
		data.queryParams.deptId = data1.deptId;
		data.curDeptName = data1.deptName;
	}
	// fetch();
};

watch(filterText, (val) => {
	treeRef.value!.filter(val);
});




const data = reactive({
	//编辑弹窗
	dialog: {
		isVisible: false,
		type: 'add',
	},

	isShowDeptMove: false,
	isShowInstallDoc: false,

	deptProps: {
		value: 'deptId',
		children: 'children',
		label: 'deptName',
	},

	preview: {
		isVisible: false,
		context: '',
	},

	queryParams: {
		keyWord: '',
		deptId: '',
		pageNum: 1,
		pageSize: 10,
	},

	selection: [],
	loading: false,

	deptData: [],
	curDeptName: '',

	tableData: {
		list: <any>[],
		total: 0,
	},

	curCommunity: <any>{},
	curCommunityCount: <any>null,
	curCommunityDoc: <any>null,
});

// 选择项
const selects = reactive<any>({
	dept: {},
	ids: [],
});

// 获取列表页数据
function fetch(data1?: any) {
	Object.assign(data.queryParams, data1);
	communityApi.getCommunityList(data.queryParams).then((res: any) => {
		data.tableData = res.data;
	});
}

// 新增
function add() {
	data.dialog.isVisible = true;
	data.dialog.type = 'add';
	edit1.value.initForm();
	edit1.value.initMap();
}

// 编辑
function doEdit(row: any) {
	data.dialog.isVisible = true;
	data.dialog.type = 'edit';
	edit1.value.initForm(JSON.parse(JSON.stringify(row)));
	if (row.longitude && row.latitude) {
		edit1.value.initMap([row.longitude, row.latitude]);
	} else {
		edit1.value.initMap();
	}
}

// 获取安装文档
function getInstallDoc(row: any) {
	data.curCommunity = row;
	const { name: comnutityName, id: communityId } = row;
	data.isShowInstallDoc = true;

	// 统计
	countCommunityDevice(communityId);

	// 获取文档
	getDocInfo(communityId);
}

// 删除
function doDelete(row: { id: any }) {
	let params = { ids: [row.id] };
	ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
		type: 'warning',
	})
		.then(() => {
			communityApi
				.delete(params)
				.then((res) => {
					ElMessage.success('删除成功');
					fetch();
				})
				.catch((err) => {
					ElMessage.error(err.message);
				});
		})
		.catch(() => null);
}

//编辑弹窗关闭
function editClose() {
	data.dialog.isVisible = false;
}

function editSuccess() {
	editClose();
	fetch();
}

//编辑弹窗关闭
function moveClose() {
	data.isShowDeptMove = false;
}

function moveSuccess() {
	moveClose();
	fetch();
}

//搜索
function search() {
	fetch();
}

//
function getDeptTreeData() {
	getDeptTree().then((res: any) => {
		res.data.deps[0].children = res.data.deps[0].children.filter((item: any) => {
			return !['安装人员', '其它', '测试'].includes(item.deptName);
		});

		data.deptData = res.data.deps;
	});
}

// 统计小区设备安装情况
function countCommunityDevice(communityId: number) {
	deviceApi.countForCommunity({ communityId }).then((res: any) => {
		data.curCommunityCount = res.data;
	});
}

// 生成安装文档
function createInstallDoc(row: any) {
	const { name: communityName, id: communityId } = row;
	if (data.curCommunityCount.unDone > 0) {
		ElMessageBox.confirm('有未完成安装的设备，确定要生成？').then(() => {
			deviceApi.createInstallDoc({ communityName, communityId }).then((res: any) => {
				data.curCommunityDoc = res.data;
			});
		});
	} else {
		deviceApi.createInstallDoc({ communityName, communityId }).then((res: any) => {
			data.curCommunityDoc = res.data;
		});
	}
}

// drawer关闭
function drawerClose() {
	data.curCommunityDoc = null;
	data.curCommunityCount = null;
}

// 获取文档信息
function getDocInfo(communityId: number) {
	communityApi.getInstallDocInfo({ communityId }).then((res: any) => {
		data.curCommunityDoc = res.data.url ? res.data : null;
	});
}

onMounted(() => {
	getDeptTreeData();
	fetch();
});
</script>

<style lang="scss" scoped>
.el-aside {
	width: auto;
}

:deep(.el-tree-node) {
	margin: 5px 0;
}
.deawerBody {
	padding: 10px;

	.statistic {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		align-items: center;
		gap: 20px;
		margin-top: 20px;

		.item {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			border: 1px solid #e4e7ed;
			border-radius: 5px;
			height: 120px;
			.title {
				font-size: 16px;
				margin-bottom: 10px;
			}
		}
	}

	table {
		border-collapse: collapse;
		border-spacing: 0px;
		margin-bottom: 20px;
	}
	table,
	th,
	td {
		padding: 5px;
		border: 1px solid #e4e7ed;
		text-align: center;
	}
}
</style>
